import { Injectable } from '@nestjs/common'
import { CreateLoginDto } from './dto/create-login.dto'
import { UpdateLoginDto } from './dto/update-login.dto'
import * as svgCaptcha from 'svg-captcha'
import { SharedService } from 'src/shared/shared.service'
import { InjectRedis } from '@nestjs-modules/ioredis'
import { CAPTCHA_IMG_KEY, USER_VERSION_KEY, USER_TOKEN_KEY } from 'src/common/constant/redis.constant'
import Redis from 'ioredis'
import { JwtService } from '@nestjs/jwt'
import { Request } from 'express'
import { Payload } from './login.interface'
import { BadRequestException } from '@nestjs/common'

@Injectable()
export class LoginService {
  constructor(
    private readonly sharedService: SharedService,
    @InjectRedis() private readonly redis: Redis,
    private readonly jwtService: JwtService,
  ) {}

  //获取登录验证码图片
  async createImageCaptcha() {
    const { data, text } = svgCaptcha.create({
      size: 4,
      ignoreChars: '0Oli',
      noise: 1,
      color: true,
      background: '#cc9966',
    })
    const result = {
      img: data.toString(),
      uuid: this.sharedService.generateUUID(),
    }
    await this.redis.set(`${CAPTCHA_IMG_KEY}:${result.uuid}`, text, 'EX', 60 * 5)
    return result
  }
  //登录接口
  async login(request: Request) {
    const { user } = request as any
    const payload: Payload = { userId: user.userId, pv: 1 }

    const jwtSign = this.jwtService.sign(payload)

    //存储密码版本号，防止登录期间 密码被管理员更改后 还能继续登录
    await this.redis.set(`${USER_VERSION_KEY}:${user.userId}`, 1)
    //存储token, 防止重复登录问题，设置token过期时间(1天后 token 自动过期)，以及主动注销token。
    await this.redis.set(`${USER_TOKEN_KEY}:${user.userId}`, jwtSign, 'EX', 60 * 60 * 24)
    return { token: jwtSign }
  }
  findOne(id: number) {
    return `This action returns a #${id} login`
  }

  update(id: number, updateLoginDto: UpdateLoginDto) {
    return `This action updates a #${id} login`
  }

  remove(id: number) {
    return `This action removes a #${id} login`
  }
}
